import router, { asyncRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar 开启进度条
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.userInfo // 获取用户信息
      if (hasGetUserInfo.username) {
        // 表示之前获取过用户信息==不需要再获取了
        next()
      } else {
        // get user info
        // await store.dispatch('user/getInfo')
        const { data: { roles: { menus }}} = await store.dispatch('user/getInfo')
        // console.log(menus, asyncRoutes, 7555)
        /* 1-根据获取的权限筛选出对应的路由匹配规则 */
        var filterRouter = asyncRoutes.filter((item) => {
          var name = item.children[0].name
          var flag = menus.includes(name)
          if (flag) {
            return item
          }
        })
        /* 2-动态添加路由匹配规则 */
        filterRouter.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRouter)
        /* 3-将动态路由传入store中 */
        store.commit('menu/setRoutes', filterRouter)
        next({ path: to.path, replace: true })
      }
      NProgress.done()
    }
  } else {
    /* has no token*/

    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar  结束进度条
  NProgress.done()
})
